package cn.xiangxiang.service.impl;

import cn.xiangxiang.CacheKey;
import cn.xiangxiang.mapper.AdMapper;
import cn.xiangxiang.pojo.business.Ad;
import cn.xiangxiang.service.business.AdService;
import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service(interfaceClass = AdService.class)
public class AdServiceImpl extends ServiceImpl<AdMapper, Ad> implements AdService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<Ad> findAdByPosition(String position) {
        List<Ad> adList = (List<Ad>) redisTemplate.boundHashOps(CacheKey.AD).get(position);
        if(adList==null) {
            QueryWrapper<Ad> wrapper = getCondition(position);
            adList = list(wrapper);
            redisTemplate.boundHashOps(CacheKey.AD).put(position,adList);
        }
        return adList;
    }

    @Override
    public void addToRedis() {
        List<String> adList = getAdPostion();
        adList.forEach((postion)->{
            redisTemplate.boundHashOps(CacheKey.AD).put(postion,findAdByPosition(postion));
        });
    }

    private List<String> getAdPostion(){
        ArrayList<String> list = new ArrayList<>();
        list.add("web_index_lb");
        return list;
    }



    private QueryWrapper<Ad> getCondition(String position) {
        QueryWrapper<Ad> wrapper = new QueryWrapper<>();
        wrapper.eq("position", position).eq("status", "1").
                lt("start_time", new Date()).gt("end_time", new Date());
        return wrapper;
    }
}
